const redis = require('ioredis');
const {info} = require("ee-core/log");
const {result} = require("lodash");

/**
 * Sequelize
 * @class
 */
class Redis {

    constructor(app) {
        this.app = app;
    }

    /**
     * 创建托盘
     */
    async create() {
        console.log(this.app)
        // 创建Redis客户端
        const client = new redis
        ({
            password: 'zzq199905',
            db: 0,
            host: '140.143.235.209', // Redis服务器地址，默认为localhost
            port: 6379,       // Redis服务器端口，默认为6379
        });
        console.log(client)
        // 处理连接错误
        client.on('error', (error) => {
            console.log(error)
            info(`[Redis] Error connecting to Redis: ${error}.`);
        });

        // 连接成功事件
        client.on('connect', () => {
            info('[Redis] Connected to Redis successfully');
        });
        // Promise async/await 封装
        //  ->查询 rides 库中是否有该Key 用于判断Token是否过期
        client.queryRedis = async function (key) {
            const res = await client.exists(key)
            if (res === 0) {
                console.log('result:<', '<' + res + '>', 'This key is null...');
                return null
            }
            console.log('Result:', '<' + res + '>', 'With this value!...');
            return res
        }
        // Promise async/await 封装
        //  ->获取 rides 库中该 Key 的 value
        client.getRedis = async function (key) {
            const result = await client.get(key)
            if (result === null) {
                console.log('result:', '<' + result + '>', 'This key cannot be find...')
                return null
            }
            console.log('Result:', '<' + result + '>', 'Get key success!...');
            return result
        }
        client.getArray = async function (key) {
            const result = await client.get(key)
            return result ? JSON.parse(result) : []
        }
        // Promise async/await 封装
        //  ->为 rides 库中的一个key 设定过期的时间 单位为秒(S)
        client.timeSetRedis = async function (key, time) {
            // 设定时间
            const result = await client.expire(key, time)
            if (result === 0) {
                console.log('Result', '<' + result + '>', 'Set defeated or key not find...');
                return null
            }
            // console.log(result);
            console.log('Result', '<' + result + '>', 'Set Success!');
            return result
        }
        client.setRedis = async function (key, value) {
            // 存储
            await client.set(key, value, (err, data) => {
                // 为key 设定一个时长 单位为S
                // client.expire(key, 60)
                if (err) {
                    console.log(err);
                }
                console.log('redis store Success!', data);
                return data //成功会返回ok
            })
        }
        this.app.redis = client
    }

}

Redis.toString = () => '[class Redis]';
module.exports = Redis;